package de.iceboy.android.goldrush.data.provider;

import java.util.Calendar;
import java.util.HashMap;

import de.iceboy.android.goldrush.Goldrush;
import de.iceboy.android.goldrush.data.provider.columns.HitSetColumns;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class HitSetProvider extends AbstractProvider {
	private static final String TAG = "GoldrushHitsetProvider";
	private static final String HITSET_TABLE_NAME = "hitset";
	private static final int HITSETS = 0;
	private static final int HITSET_BY_ID = 1;
	private static final Uri CONTENT_URI = Uri.parse("content://" + Goldrush.AUTHORITY + "/" + Goldrush.HITSET_URI_PART);


	private static final UriMatcher uriMatcher;
	private static HashMap<String, String> projectionMap;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DataBackend.DATABASE_NAME, null, DataBackend.DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE " + HITSET_TABLE_NAME + " (" + HitSetColumns._ID + " INTEGER PRIMARY KEY,"
					+ HitSetColumns.ROUND_ID + " INT,"+ HitSetColumns.DESCRIPTION + " TEXT," + HitSetColumns.DELETED + " INT," + HitSetColumns.TIMESTAMP + " INT"
					+ ");");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO: implement upgrade procedure here if needed
			onCreate(db);
		}
	}

	private de.iceboy.android.goldrush.data.provider.HitSetProvider.DatabaseHelper sqliteHelper;

	@Override
	public boolean onCreate() {
		sqliteHelper = new DatabaseHelper(getContext());
		sqliteHelper.getWritableDatabase();
		return true;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		SQLiteDatabase db = sqliteHelper.getWritableDatabase();
		int count;
		switch (uriMatcher.match(uri)) {
		case HITSETS:
			count = db.delete(HITSET_TABLE_NAME, selection, selectionArgs);
			break;
		case HITSET_BY_ID:
			String noteId = uri.getPathSegments().get(1);
			count = db.delete(HITSET_TABLE_NAME, HitSetColumns._ID + "=" + noteId
					+ (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
			break;

		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public String getType(Uri uri) {
		switch (uriMatcher.match(uri)) {
		case HITSETS:
			return HitSetColumns.HITSETS_TYPE;
		case HITSET_BY_ID:
			return HitSetColumns.HITSET_TYPE;

		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
        if (values == null)
        	return null;
        if(values.getAsInteger(HitSetColumns.ROUND_ID) == null)
        	throw new SQLException(HitSetColumns.ROUND_ID + " cannot be null");
        setDefaultIfUnset(values, HitSetColumns.DESCRIPTION, "");
        setDefaultIfUnset(values, HitSetColumns.TIMESTAMP, Calendar.getInstance().getTimeInMillis());
        setDefaultIfUnset(values, HitSetColumns.DELETED, 0);
        try{
            SQLiteDatabase db = sqliteHelper.getWritableDatabase();
            long rowId = db.insert(HITSET_TABLE_NAME, HitSetColumns.DESCRIPTION, values);
            if (rowId > 0) {
                Uri noteUri = ContentUris.withAppendedId(CONTENT_URI, rowId);
                getContext().getContentResolver().notifyChange(noteUri, null);
                return noteUri;
            }
        }catch(Exception e){
        	Log.d("myliveshopping", e.getMessage());
        	return null;
        }
        throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

        switch (uriMatcher.match(uri)) {
        case HITSETS:
            qb.setTables(HITSET_TABLE_NAME);
            qb.setProjectionMap(projectionMap);
            break;

        case HITSET_BY_ID:
            qb.setTables(HITSET_TABLE_NAME);
            qb.setProjectionMap(projectionMap);
            qb.appendWhere(HitSetColumns._ID + "=" + uri.getPathSegments().get(1));
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        // If no sort order is specified use the default
        String orderBy;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = HitSetColumns.DEFAULT_SORT_ORDER;
        } else {
            orderBy = sortOrder;
        }

        // Get the database and run the query
        SQLiteDatabase db = sqliteHelper.getReadableDatabase();
        //Log.d("myliveshopping", qb.buildQuery( projection, selection, selectionArgs, null, null, orderBy, null));
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
        
        // Tell the cursor what uri to watch, so it knows when its source data changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        SQLiteDatabase db = sqliteHelper.getWritableDatabase();
        int count;
        switch (uriMatcher.match(uri)) {
        case HITSETS:
            String productId = uri.getPathSegments().get(1);
            count = db.update(HITSET_TABLE_NAME, values, HitSetColumns._ID + "=" + productId
                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
            break;
        case HITSET_BY_ID:
            count = db.update(HITSET_TABLE_NAME, values, selection, selectionArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}

	static {
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		uriMatcher.addURI(Goldrush.AUTHORITY, Goldrush.HITSET_URI_PART, HITSETS);
		uriMatcher.addURI(Goldrush.AUTHORITY, Goldrush.HITSET_URI_PART + "/#", HITSET_BY_ID);

		projectionMap = new HashMap<String, String>();
		projectionMap.put(HitSetColumns._ID, HitSetColumns._ID);
		projectionMap.put(HitSetColumns.ROUND_ID, HitSetColumns.ROUND_ID);		
		projectionMap.put(HitSetColumns.DESCRIPTION, HitSetColumns.DESCRIPTION);
		projectionMap.put(HitSetColumns.TIMESTAMP, HitSetColumns.TIMESTAMP);
		projectionMap.put(HitSetColumns.DELETED, HitSetColumns.DELETED);
	}

}
